// pages/demo/uploadOss/uploadOss.js
const app = getApp()
var httpUtils = require("../../utils/httpUtils.js")
var util = require("../../utils/util.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    "imgArr": [],
    "testShowText":"123"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(this.data.testShowText);
    var imgArr = this.data.imgArr;
    // imgArr.push(util.getOssSmallPicUrl("http://baiying-order.oss-cn-hangzhou.aliyuncs.com/test/2018626113252520.JPG"));
    // imgArr.push(util.getOssSmallPicUrl("http://baiying-order.oss-cn-hangzhou.aliyuncs.com/test/2018626113252520.JPG"));
    // imgArr.push(util.getOssSmallPicUrl("http://baiying-order.oss-cn-hangzhou.aliyuncs.com/test/2018626113252520.JPG"));
    // this.setData({
    //   testShowText:"222",
    //   imgArr : imgArr
    // })
  },


  upload_oss: function (event) {
    var _this = this;
    console.log(event);
    var order_id = event.currentTarget.dataset.order_id;
    //第一步，先获取oss需要的签证信息
    _this.getOssToken(order_id);



    wx.chooseImage({
      count: 3,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        var oss_policy_key = "oss_policy_key";
        var oss_policy_info = wx.getStorageSync(oss_policy_key);
        console.info(oss_policy_info.policy);
        console.info(oss_policy_info.OSSAccessKeyId);
        console.info(oss_policy_info.signature);

        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        //启动上传等待中...  
        
        var uploadImgCount = tempFilePaths.length;
        wx.showLoading({
          title: "1/" + uploadImgCount,
          mask: true
        })

        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          console.log(tempFilePaths[i]);
          var fileName = util.getFomcatNowTime() + util.getFileSuffix(tempFilePaths[i]);
          var babyData = {
            'key': order_id + "/" + fileName,
            'policy': oss_policy_info.policy,
            'OSSAccessKeyId': oss_policy_info.OSSAccessKeyId,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204  
            'signature': oss_policy_info.signature
          }
          
           _this.uploadFileAli(babyData, tempFilePaths[i], uploadImgCount, i);
        }
      }
    })
  },

  uploadFileAli: function (babyData, filePath, uploadImgCount, i) {
    console.log((i+1) + "/" + uploadImgCount + "  [" + filePath + "]");
    var _this = this;
    wx.uploadFile({
      url: app.globalData.uploadUrl,
      formData: babyData,
      name: 'file',
      filePath: filePath,
      header: {
        'content-type': 'multipart/form-data'
      },
      success: function(res){
          console.log("uploadFile success",res);
          if (res.statusCode == 200) {
              //表示上传成功(可以在阿里云服务器查看上传的图片)

              var fileUrl = app.globalData.uploadPreUrl + "/" + babyData.key;
              console.log("fileUrl:" + fileUrl)


              var imgArr = _this.data.imgArr;
              imgArr.push(util.getOssSmallPicUrl(fileUrl));
              _this.setData({
                  imgArr : imgArr
              })


              //如果是最后一张,则隐藏等待中
              if (uploadImgCount - 1 == i) {
                  wx.hideLoading();
                  wx.showToast({
                      title: '上传成功',
                      icon: 'success',
                      duration: 2000
                  })
              }else{
                  wx.showLoading({
                      title: (i + 2) + "/" + uploadImgCount,
                      mask: true
                  })
              }
          } else {
              if (uploadImgCount - 1 == i) {
                  wx.hideToast();
                  wx.showToast({
                      title: '上传失败',
                      icon: 'none',
                      duration: 2000
                  })
              }
          }
      },
      fail: function(res) {
          console.log("uploadFile fail",res);
      }
    })

  },


  /**
     * 先从缓存中取，如果取不到，调用网络接口重新获取，让后存入缓存中
     * 
     */
  getOssToken: function (order_id) {
    var _this = this;
    console.log("getOssToken--------------------")

    var url = app.globalData.interfaceUrl + '/alibaba/getOssPolicyInfo.do';
    //写入参数  
    var params = { orderId: order_id }
    httpUtils.post(url, params,  function (res) {
      //res就是我们请求接口返回的数据
      var policyBean = res.data.data;
      console.log('这就不好了吧')
      console.log(JSON.stringify(res));
      var oss_policy_info = {
        "policy": policyBean.policy,
        "OSSAccessKeyId": policyBean.accessid,
        "signature": policyBean.signature
      }
      wx.setStorageSync("oss_policy_key", oss_policy_info)

    }, function (res) {
      console.log('错误');
      console.log(JSON.stringify(res));
    })

  },
  previewImg: function (e) {
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var imgArr = this.data.imgArr;
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})